#pragma once

#include "../ConnectionLibrary.h"
#include "ClientConnectionsManager.h"

#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/thread.hpp>

#include <list>

namespace AlgoTrading
{
	namespace ConnectionLibrary
	{
		class ServerConnectionLibraryImpl : public ServerConnectionLibrary
		{
		public:
			ServerConnectionLibraryImpl(ClientConnectionAcceptorPtr acceptor, const std::string& address, const std::string& port);
			virtual ~ServerConnectionLibraryImpl(void);

			virtual void Start();
			virtual void Stop();
		private:
			void ProcessingCycle();

			ClientConnectionAcceptorPtr connectionAcceptor;
			std::auto_ptr<boost::asio::io_service> io_service;
			typedef std::list<std::tr1::shared_ptr<boost::thread>> ThreadsList;
			ThreadsList threads;


			/// Handle completion of an asynchronous accept operation.
			void HandleAccept(const boost::system::error_code& e);

			/// Handle a request to stop the server.
			void HandleStop();

			/// Acceptor used to listen for incoming connections.
			boost::asio::ip::tcp::acceptor acceptor;

			/// Socket for the next connection to be accepted.
			std::auto_ptr<boost::asio::ip::tcp::socket> newConnectionSocket;
			
			ClientConnectionsManager connectionManager;

			std::string address;
			std::string port;

			bool started;
		};
	}
}